<?php
/**
 * 添加会员
 * Created by PhpStorm.
 * User: eric
 * Date: 2020/7/22
 * Time: 12:16
 */

namespace App\Admin\Extensions\Action;

use App\Models\FarmOrderPick;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderPick extends RowAction
{

    public $name = '提货';

    protected $selector = '.add-pick';

    public function handle(Model $model, Request $request)
    {
        //处理逻辑
        $num     = $request->input('add_num');
        $total   = $model->total_num;
        $hadPick = $model->pick_up_num;
        if (!is_numeric($num)) {
            return $this->response()->error('数量不合规范');
        }
        if ($model->status == -1 || $model->status == 0) {
            return $this->response()->error('订单未支付或已取消,不可提货');
        }
        if ($model->status == 2) {
            return $this->response()->error('订单已完成,不可提货');
        }
        if ($total < ($hadPick + $num)) {
            return $this->response()->error('提货数量超过订单总量');
        }
        $last_num = $total - $hadPick - $num;

        try {
            DB::beginTransaction();
            $model->pick_up_num      = $model->pick_up_num + $num;
            $model->last_surplus_num = $last_num;
            if ($total == ($hadPick + $num)) {//全部提货完
                $model->status = 2;
            }
            $model->save();
            FarmOrderPick::create(['order_id' => $model->id, 'user_id' => $model->user_id, 'address' => $model->address, 'pickup_num' => $num, 'total_num' => $total, 'surplus_num' => $last_num, 'pickup_time' => time()]);
            DB::commit();
            return $this->response()->success('提货成功')->refresh();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error('提货失败');
        }
    }

    public function form()
    {
        $this->text('add_num', '提货数量')->attribute(['autocomplete' => 'off']);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default add-pick" title="订单提货">订单提货</a>
HTML;
    }


}
